<template>
  <!-- 用户列表模块 -->
  <div class="userListContainer">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="handleClearAble"
          >
            <el-button slot="append" icon="el-icon-search" @click="queryUesrList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="usersListTable" border stripe>
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="姓名" prop="username" align="center"></el-table-column>
        <el-table-column label="电话" prop="mobile" align="center"></el-table-column>
        <el-table-column label="角色" prop="role_name" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加用户的dialog对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addUserDialogVisiable"
        @close="handleAddClose"
        @open="handleAddOpen"
      >
        <!-- 添加用户的表单区域 -->
        <el-form
          :model="addUserForm"
          ref="addUserFormRef"
          :rules="addUserFormRules"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="handleAddUserClick">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑用户的dialog对话框 -->
      <el-dialog title="修改用户信息" :visible.sync="editUserDialogVisiable" @close="handleEditClose">
        <!-- 添加用户的表单区域 -->
        <el-form
          :model="editUserForm"
          ref="editUserFormRef"
          :rules="editUserFormRules"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="handleEditUserClick">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisiable" @close="handleSetRoleClose">
        <!-- 添加用户的表单区域 -->
        <el-form ref="setRoleFormRef" label-width="100px">
          <el-form-item label="当前用户：">
            <span>{{userInfo.username}}</span>
          </el-form-item>
          <el-form-item label="当前角色：">
            <span>{{userInfo.role_name}}</span>
          </el-form-item>
          <el-form-item label="当前角色：">
            <el-select v-model="roleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="handleSetRoleClick">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { checkEmail, checkMobile } from '../../utils/index'
export default {
  data() {
    // 验证邮箱
    var vaildateEmail = (rule, value, cb) => {
      // 不能为空
      if (!value) {
        return cb(new Error('请输入邮箱号'))
      }
      // 验证邮箱格式
      if (value && checkEmail(value)) return cb()
      // 验证失败
      cb(new Error('请输入正确的邮箱号！！！'))
    }

    // 验证手机号
    var vaildateMobile = (rule, value, cb) => {
      // 不能为空
      if (!value) {
        return cb(new Error('请输入手机号码'))
      }
      // 验证手机格式
      if (value && checkMobile(value)) return cb()
      // 验证失败
      cb(new Error('请输入正确的手机号码'))
    }
    return {
      // 查询参数的对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表的表格数据数组
      usersListTable: [],
      // 定义总页码数
      total: 0,
      // 控制添加用户的对话框显示和隐藏
      addUserDialogVisiable: false,
      // 添加用户的表单
      addUserForm: {
        username: '', // 用户名
        password: '', // 密码
        email: '', // 邮箱
        mobile: '' // 手机
      },
      // 添加用户的表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在6-15位之间', trigger: 'blur' }
        ],
        email: [{ validator: vaildateEmail, trigger: 'blur' }],
        mobile: [{ validator: vaildateMobile, trigger: 'blur' }]
      },
      // 控制修改用户的对话框显示和隐藏
      editUserDialogVisiable: false,
      // 修改用户的表单
      editUserForm: {},
      // 修改用户的表单验证规则
      editUserFormRules: {
        email: [{ validator: vaildateEmail, trigger: 'blur' }],
        mobile: [{ validator: vaildateMobile, trigger: 'blur' }]
      },
      // 控制分配角色的对话框显示和隐藏
      setRoleDialogVisiable: false,
      // 用户的信息
      userInfo: {},
      // 角色列表
      roleList: [],
      // 角色id
      roleId: ''
    }
  },
  created() {
    this.getUsersList()
  },

  methods: {
    // 获取用户列表数据
    async getUsersList() {
      const { data: res } = await this.$axios.get('users', {
        params: {
          ...this.queryInfo
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表数据失败')
      }
      // 赋值给用户列表
      this.usersListTable = res.data.users
      // 获取总页数
      this.total = res.data.total
    },

    // 点击按钮根据搜索内容查询用户
    queryUesrList() {
      this.getUsersList()
    },

    // 处理清空搜索框回调函数
    handleClearAble() {
      this.getUsersList()
    },

    // 处理切换每页大小函数
    handleSizeChange(size) {
      this.queryInfo.pagesize = size
      this.queryInfo.pagenum = 1
      this.getUsersList()
    },
    // 处理切换当前页的函数
    handleCurrentChange(cpage) {
      this.queryInfo.pagenum = cpage
      this.getUsersList()
    },

    // 点击按钮添加用户
    addUser() {
      // 显示添加用户的对话框
      this.addUserDialogVisiable = true
    },
    // 处理关闭添加用户dialog对话框
    handleAddClose() {
      this.$refs['addUserFormRef'].resetFields()
    },
    // 处理打开添加用户的dialog对话框
    handleAddOpen() {
      // 自动获取焦点
      this.$nextTick(_ => {
        this.$refs['addUserFormRef'].$el[0].focus()
      })
    },
    // 点击确认按钮添加用户
    handleAddUserClick() {
      // 预处理表单
      this.$refs['addUserFormRef'].validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.post('users', {
            ...this.addUserForm
          })
          // 添加失败
          if (res.status !== 201) {
            return this.$message.error('添加用户失败！！！')
          }

          // 提示添加成功
          this.$message({
            type: 'success',
            message: '添加用户成功'
          })
          // 关闭对话框
          this.addUserDialogVisiable = false
          // 重新请求数据
          this.getUsersList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 点击按钮展示修改用户的id
    async editUser(id) {
      const { data: res } = await this.$axios.get(`users/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败!!!')
      }

      this.editUserForm = res.data
      this.editUserDialogVisiable = true
    },
    // 处理关闭修改用户信息dialog对话框
    handleEditClose() {
      this.$refs['editUserFormRef'].resetFields()
    },
    // 点击确定按钮修改用户信息
    handleEditUserClick() {
      // 修改用户信息的表单预处理
      this.$refs['editUserFormRef'].validate(async valid => {
        // 验证成功
        if (valid) {
          const { data: res } = await this.$axios.put(
            `users/${this.editUserForm.id}`,
            {
              email: this.editUserForm.email,
              mobile: this.editUserForm.mobile
            }
          )

          if (res.meta.status !== 200) {
            return this.$message.error('修改用户信息失败！！！')
          }

          // 提示修改成功
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          // 重置editUserForm对象
          this.editUserForm = {}
          // 关闭对话框
          this.editUserDialogVisiable = false
          // 刷新数据
          this.getUsersList()
        } else {
          console.log('edit form error!!!')
          return false
        }
      })
    },

    // 监听switch状态的改变
    async userStateChanged(userinfo) {
      const { data: res } = await this.$axios.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )

      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }

      // 更新成功
      console.log(res.meta.msg)
    },

    // 点击按钮删除用户
    async removeUserById(id) {
      // 确认是否删除
      const confirmResult = await this.MessageBox.confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.Notification.info({
          title: '消息',
          message: '取消了删除操作'
        })
      }

      // 执行操作步骤
      const { data: res } = await this.$axios.delete(`users/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！！！')
      }

      // 提示删除成功
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      // 刷新用户列表
      this.getUsersList()
    },

    // 分配角色
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 获取所有的角色
      const { data: res } = await this.$axios.get('roles')
      // 获取角色列表失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败！！！')
      }
      this.roleList = res.data
      // 显示对话框
      this.setRoleDialogVisiable = true
    },

    // 监听关闭分配角色的对话框
    handleSetRoleClose() {
      this.roleId = ''
    },

    // 监听点击确认分配角色按钮
    async handleSetRoleClick() {
      const { data: res } = await this.$axios.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.roleId }
      )
      // 分配角色失败
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      // 提示
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      // 刷新用户列表数据
      this.getUsersList()
      // 关闭对话框
      this.setRoleDialogVisiable = false
    }
  }
}
</script>

<style>
</style>
